package server;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import javax.imageio.ImageIO;

import com.googlecode.javacv.FFmpegFrameRecorder;
import com.googlecode.javacv.FrameRecorder;
import com.googlecode.javacv.FrameRecorder.Exception;
import com.googlecode.javacv.cpp.avutil;
import com.googlecode.javacv.cpp.opencv_core.IplImage;


//这个服务器接受的是图片，server函数返回一个BufferdImage，交给process函数处理，process函数负责将BufferedImage
//存到本地。
public class ImgServer implements Runnable{
	public static final int PORT = 4000;
	private DatagramSocket dataSocket;
	private DatagramPacket dataPacket;
	private byte receiveByte[];
	private static int BUFSIZE = 1024;
	private boolean work = true;
	
	public ImgServer() throws SocketException{
		dataSocket = new DatagramSocket(PORT);
		receiveByte = new byte[BUFSIZE];
		dataPacket = new DatagramPacket(receiveByte, BUFSIZE);
	}
	
	public BufferedImage server() throws IOException{
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		ByteArrayInputStream bin;
		BufferedImage bimage = null;
		int bufSize = 0;
		int i = 0;
		while (i == 0)// 无数据，则循环
		{
			dataSocket.receive(dataPacket);
			i = dataPacket.getLength();
			bufSize += i;
			// 接收数据
		//	 System.out.println("server " + i);
			if (i > 0) {
				bout.write(dataPacket.getData(), 0, i);
				i = 0;// 循环接收
				
				continue;
			}
			
			break;
		}

	
		bin = new ByteArrayInputStream(bout.toByteArray());
		try {
			bimage = ImageIO.read(bin);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		bout.close();
		bin.close();
		return bimage;
		
	}
	
	//该函数负责调用server函数，并将其返回的BufferedImage存到本地
	public void  saveAsImage() throws IOException{
		BufferedImage bimage = server();
		File file = new File(System.currentTimeMillis()+".jpg");
		System.out.println("ImageIo");
		ImageIO.write(bimage, "jpg", file);
	}
	
	public void run(){
		try {
			while(work){
				saveAsVedio();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private boolean writerIsNull = true;
	private FFmpegFrameRecorder writer;
	public void saveAsVedio() throws IOException, Exception{
		BufferedImage bimage = server();
		if(writerIsNull){
			writer = new FFmpegFrameRecorder("test.mp4",  bimage.getWidth(),bimage.getHeight());
			writer.setVideoCodec(13);
			writer.setFormat("mp4");
			writer.setPixelFormat(avutil.AV_PIX_FMT_YUV420P);
			writer.setFrameRate(25);
			writer.setVideoBitrate(10 * 1024 * 1024);
			writerIsNull = false;
			writer.start();
			System.out.println("Video Writer created!");
		}
		writeFrame2Vedio(bimage);
	}
	
	
	int count_ =  30;
	public void writeFrame2Vedio(BufferedImage bimage) throws Exception{
		IplImage image = IplImage.createFrom(bimage);
//		opencv_highgui.cvWriteFrame(writer,image);
		writer.record(image);
		System.out.println("write a image in");
		if(count_ --  == 0){
			work = false;
			writer.stop();
			System.out.println("Video Writer closed!");
		}
	}
	
	public static void main(String[] args) throws InterruptedException{
		ImgServer server = null;
		try {
			server = new ImgServer();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Thread thread = new Thread(server);
		thread.start();
	
	}

	private  void stopServer() {
		// TODO Auto-generated method stub
		work = false;
	}
}
